<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/2/7
 * Time: 23:53
 */
declare(strict_types=1);

namespace App\Service;
use App\Model\Dao\MchAccountAccessDao;
use App\Model\Dao\MchAccountAccessDetailDao;
use App\Model\Dao\MchAccountDao;
use App\Model\Dao\RateSettleDao;
use App\Model\Dao\TradeOrderDetailDao;
use App\Model\Dao\TradeOrderRefundDao;
use App\Utils\CustomUtils;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Exception;

/**
 * Class SettleTradeOrderRefundService
 * @package App\Service
 * 交易订单退款结算
 */
class SettleTradeOrderRefundService extends CommonService
{

    /**
     * @Inject()
     * @var TradeOrderRefundDao
     */
    private $TradeOrderRefundDao;

    /**
     * @Inject()
     * @var TradeOrderDetailDao
     */
    private $TradeOrderDetailDao;

    /**
     * @Inject()
     * @var MchAccountDao
     */
    private $MchAccountDao;

    /**
     * @Inject()
     * @var MchAccountAccessDao
     */
    private $MchAccountAccessDao;

    /**
     * @Inject()
     * @var MchAccountAccessDetailDao
     */
    private $MchAccountAccessDetailDao;

    /**
     * @Inject()
     * @var RateSettleDao
     */
    private $RateSettleDao;

    public function handle($param) {
        // 校验
        $tradeOrderRefund = $this->TradeOrderRefundDao->get($param['refundId']);
        if(!$tradeOrderRefund) {
            throw new Exception('退款单不存在，终止处理', FAILED_CODE);
        }
        if($tradeOrderRefund['handleStatus'] != $param['handleStatus']) {
            throw new Exception('退款单处理状态不对应', FAILED_CODE);
        }
        if($tradeOrderRefund['settleStatus'] == 1) {
            throw new Exception('退款单已结算完成', FAILED_CODE);
        }
        $tradeOrder = $this->TradeOrderDetailDao->get($tradeOrderRefund['orderId']);
        if($tradeOrder['isSettle'] != 2) {
            throw new Exception('退款单原始交易订单未结算', FAILED_CODE);
        }
        $mchAccount = $this->MchAccountDao->get($param['mchAccountId']);
        if(!$mchAccount) {
            throw new Exception('查询账户记录失败', FAILED_CODE);
        }
        $isDetail = $this->MchAccountAccessDetailDao->getWhere([
            "refundId" => $tradeOrderRefund['id'],
            "type"     => TYPE_TRADE_ORDER_REFUND_CASH_OUT,
        ]);

        if ($param['handleStatus'] == 0) {
            if ($isDetail && empty($isDetail['accessId'])) {
                throw new Exception('交易退款单已冻结结算', FAILED_CODE);
            }
            return $this->handleAdd($param, $tradeOrder, $tradeOrderRefund, $mchAccount);
        } else {
            // 初审通过不用管
            if ($param['handleStatus'] == 1) {
                return $this->handleFirstConfirm($tradeOrderRefund);
            }
            if ($isDetail && !empty($isDetail['accessId'])) {
                throw new Exception('交易退款单请先发起冻结结算', FAILED_CODE);
            }
            return $this->handleConfirm($param, $tradeOrder, $tradeOrderRefund, $mchAccount);
        }
    }

    private function handleFirstConfirm($tradeOrderRefund) {
        Db::beginTransaction();
        try {
            $this->TradeOrderRefundDao->set($tradeOrderRefund['id'], [
                'settleStatus'  => 1,
            ]);
        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
            Db::rollBack();
            return CustomUtils::xeServiceReturnData(FAILED_CODE, "交易订单退款初审结算失败");
        }
        Db::commit();
        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "交易订单退款初审通过结算成功");
    }

    /**
     * @param $param
     * @param $tradeOrder
     * @param $tradeOrderRefund
     * @param $mchAccount
     * @return array
     * @throws Exception
     * 新增退款记录，出入账
     */
    public function handleAdd($param, $tradeOrder, $tradeOrderRefund, $mchAccount) {

        // 乐观锁版本号+1
        $updateVersion = $mchAccount['updateVersion'] + 1;
        $transSettleAmount = $tradeOrderRefund['transSettleAmount'];

        // 交易可提现金额 余额前后
        $beforeTradeCashAmount = $mchAccount['tradeCashAmount'];
        $afterTradeCashAmount  = $mchAccount['tradeCashAmount'] - $transSettleAmount;

        // 交易冻结金额 余额前后
        $beforeTradeFrozenAmount = $mchAccount['tradeFrozenAmount'];
        $afterTradeFrozenAmount = $mchAccount['tradeFrozenAmount'] + $transSettleAmount;

        // 开启事务
        Db::beginTransaction();
        try {
            // step
            // 1.可提现出账
            // 2.可提现入账
            // 3.更新退款单
            // 4.更新账户
            $this->handleCashOutTransAmount($param, $tradeOrderRefund, $mchAccount, $transSettleAmount, $beforeTradeCashAmount, $afterTradeCashAmount);

            $this->handleFrozenInTransAmount($param, $tradeOrderRefund, $mchAccount, $transSettleAmount, $beforeTradeFrozenAmount, $afterTradeFrozenAmount);

            $this->TradeOrderRefundDao->set($tradeOrderRefund['id'], [
                'settleStatus'  => 1,
            ]);

            $updateMchAccount = array(
                "tradeCashAmount"   => $afterTradeCashAmount,
                "tradeFrozenAmount" => $afterTradeFrozenAmount,
                "updateVersion"     => $updateVersion
            );
            $result = $this->MchAccountDao->updateWhere([
                "id" => $param['mchAccountId'],
                "updateVersion" => $mchAccount['updateVersion']
            ], $updateMchAccount);

            // 如果更新账户失败，重试，最多3次
            if (!$result) {
                throw new \Exception("更新账户失败");
            }

        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
            Db::rollBack();

            // 失败重试，最多3次
            $this->tryOneMore($param);

            return CustomUtils::xeServiceReturnData(FAILED_CODE, "交易退款单结算失败");
        }
        Db::commit();

        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "交易退款单结算成功");
    }

    /**
     * @param $param
     * @param $tradeOrder
     * @param $tradeOrderRefund
     * @param $mchAccount
     * @return array
     * @throws Exception
     * 退款单，审核，出入账
     */
    private function handleConfirm($param, $tradeOrder, $tradeOrderRefund, $mchAccount) {
        // 乐观锁版本号+1
        $updateVersion = $mchAccount['updateVersion'] + 1;
        $transSettleAmount = $tradeOrderRefund['transSettleAmount'];

        // 交易可提现金额，解冻金额，余额前后
        $beforeFrozenTradeCashAmount = $mchAccount['tradeCashAmount'];
        $afterFrozenTradeCashAmount  = $mchAccount['tradeCashAmount'] + $transSettleAmount;

        // 交易冻结金额，解冻金额，余额前后
        $beforeFrozenTradeFrozenAmount = $mchAccount['tradeFrozenAmount'];
        $afterFrozenTradeFrozenAmount = $mchAccount['tradeFrozenAmount'] - $transSettleAmount;

        // 交易可提现金额，出账，余额前后
        $beforeRefundTradeCashAmount = $afterFrozenTradeCashAmount;
        $afterRefundTradeCashAmount  = $afterFrozenTradeCashAmount - $transSettleAmount;

        // 交易可提现金额，扣退款手续费，余额前后
        $refundFee = 0;
        $beforeRefundFeeTradeCashAmount = 0;
        $afterRefundFeeTradeCashAmount  = 0;
        if ($param['handleStatus'] == 3) {
            $rateSettle = $this->RateSettleDao->getByMchId($tradeOrder['mchId']);
            if(!$rateSettle) {
                throw new Exception('查询商户结算费率失败', FAILED_CODE);
            }
            $refundFee = $rateSettle['refundFee'];
            $beforeRefundFeeTradeCashAmount = $afterRefundTradeCashAmount;
            $afterRefundFeeTradeCashAmount = $beforeRefundFeeTradeCashAmount - $refundFee;
        }

        // 开启事务
        Db::beginTransaction();
        try {
            // step
            // 1.解冻交易冻结出账
            // 2.解冻交易可提现入账
            // 3.复审成功，交易可提现出账
            // 4.复审成功，新增退款手续费
            // 5.更新退款订单结算状态
            // 6.复审成功，才会更新订单退款金额，退款结算金额
            // 7.更新账户

            // step 1
            $accessId = $this->handleConfirmFrozenOutTransAmount($param, $tradeOrderRefund, $mchAccount, $transSettleAmount, $beforeFrozenTradeFrozenAmount, $afterFrozenTradeFrozenAmount);

            // handleAdd新增时添加的记录，查询
            $frozenInDetail = $this->MchAccountAccessDetailDao->getWhere(['refundId'  => $tradeOrderRefund['id'], 'type' => TYPE_TRADE_ORDER_REFUND_FROZEN_IN]);

            $this->MchAccountAccessDetailDao->update($frozenInDetail['id'], ['accessId' => $accessId]);

            // step 2
            $confirmCashInId = $this->handleConfirmCashInTransAmount($param, $tradeOrderRefund, $mchAccount, $transSettleAmount, $beforeFrozenTradeCashAmount, $afterFrozenTradeCashAmount);

            // step 3
            if ($param['handleStatus'] == 3) {
                $accessId = $this->handleConfirmCashOutTransAmount($param, $tradeOrderRefund, $mchAccount, $transSettleAmount, $beforeRefundTradeCashAmount, $afterRefundTradeCashAmount);

                $this->MchAccountAccessDetailDao->update($confirmCashInId, ['accessId' => $accessId]);

                // handleAdd新增时添加的记录，查询
                $cashOutDetail = $this->MchAccountAccessDetailDao->getWhere(['refundId'  => $tradeOrderRefund['id'], 'type' => TYPE_TRADE_ORDER_REFUND_CASH_OUT]);

                $this->MchAccountAccessDetailDao->update($cashOutDetail['id'], ['accessId' => $accessId]);

                // step 6
                $this->handleConfirmRefundFee($param, $tradeOrderRefund, $mchAccount, $refundFee, $beforeRefundFeeTradeCashAmount, $afterRefundFeeTradeCashAmount);
            }

            // step 7
            $this->TradeOrderRefundDao->set($tradeOrderRefund['id'], [
                'settleStatus'  => 1,
                'settleTime'    => time()
            ]);

            // 审核成功
            if ($param['handleStatus'] == 3) {
                // step 8
                $this->TradeOrderDetailDao->set($tradeOrder['id'], [
                    'refundFee'             => $refundFee
                ]);

                // step 9
                $updateMchAccount = array(
                    "tradeCashAmount"   => $afterRefundFeeTradeCashAmount,
                    "tradeFrozenAmount" => $afterFrozenTradeFrozenAmount,
                    "updateVersion"     => $updateVersion
                );
            } else {
                // step 9
                $updateMchAccount = array(
                    "tradeCashAmount"   => $afterFrozenTradeCashAmount,
                    "tradeFrozenAmount" => $afterFrozenTradeFrozenAmount,
                    "updateVersion"     => $updateVersion
                );
            }
            $result = $this->MchAccountDao->updateWhere([
                "id" => $param['mchAccountId'],
                "updateVersion" => $mchAccount['updateVersion']
            ], $updateMchAccount);

            // 如果更新账户失败，重试，最多3次
            if (!$result) {
                throw new \Exception("更新账户失败");
            }

        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
            Db::rollBack();

            // 失败重试，最多3次
            $this->tryOneMore($param);

            return CustomUtils::xeServiceReturnData(FAILED_CODE, "交易退款单审核结算失败");
        }
        Db::commit();

        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "交易退款单审核结算成功");
    }

    /**
     * @param $param
     * @param $tradeOrderRefund
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 提交记录，退款金额，可提现出账
     */
    private function handleCashOutTransAmount($param, $tradeOrderRefund, $mchAccount, $amount, $beforeAmount, $afterAmount) {

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderRefund["mchId"],
            "mchNo"             => $tradeOrderRefund["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_TRADE_ORDER_REFUND_CASH_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "currency"          => $tradeOrderRefund['transSettleCurrency'],
            "orderId"           => $tradeOrderRefund['orderId'],
            "tradeNo"           => $tradeOrderRefund['tradeNo'],
            "refundId"          => $tradeOrderRefund['id'],
            "remark"            => "交易订单退款冻结可提现账户出账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }

    /**
     * @param $param
     * @param $tradeOrderRefund
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 提交记录，退款金额，冻结金额入账
     */
    private function handleFrozenInTransAmount($param, $tradeOrderRefund, $mchAccount, $amount, $beforeAmount, $afterAmount) {

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderRefund["mchId"],
            "mchNo"             => $tradeOrderRefund["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accountType"       => ACCOUNT_TYPE_CASH_FROZEN,
            "inOutType"         => DETAIL_TYPE_IN,
            "type"              => TYPE_TRADE_ORDER_REFUND_FROZEN_IN,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => $amount,
            "currency"          => $tradeOrderRefund['transSettleCurrency'],
            "orderId"           => $tradeOrderRefund['orderId'],
            "tradeNo"           => $tradeOrderRefund['tradeNo'],
            "refundId"          => $tradeOrderRefund['id'],
            "remark"            => "交易订单退款冻结冻结账户入账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }

    /**
     * @param $param
     * @param $tradeOrderRefund
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * @return string
     * 审核，退款金额，可提现入账
     */
    private function handleConfirmCashInTransAmount($param, $tradeOrderRefund, $mchAccount, $amount, $beforeAmount, $afterAmount) {
        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderRefund["mchId"],
            "mchNo"             => $tradeOrderRefund["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_IN,
            "type"              => TYPE_TRADE_ORDER_REFUND_CONFIRM_CASH_IN,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => $amount,
            "currency"          => $tradeOrderRefund['transSettleCurrency'],
            "orderId"           => $tradeOrderRefund['orderId'],
            "tradeNo"           => $tradeOrderRefund['tradeNo'],
            "refundId"          => $tradeOrderRefund['id'],
            "remark"            => "交易订单退款冻结可提现账户入账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
        return $mchAccountAccessDetail['id'];
    }

    /**
     * @param $param
     * @param $tradeOrderRefund
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * @return string
     * 确认，退款金额，冻结金额出账
     */
    private function handleConfirmFrozenOutTransAmount($param, $tradeOrderRefund, $mchAccount, $amount, $beforeAmount, $afterAmount) {
        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $tradeOrderRefund["mchId"],
            "mchNo"        => $tradeOrderRefund["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_TRADE_ORDER_REFUND,
            "accountType"  => ACCOUNT_TYPE_CASH_FROZEN,
            "orderId"      => $tradeOrderRefund['orderId'],
            "tradeNo"      => $tradeOrderRefund['tradeNo'],
            "refundId"     => $tradeOrderRefund['id'],
            "amount"       => 0,
            "currency"     => $tradeOrderRefund['transSettleCurrency'],
            "status"       => 1,
            "isShow"       => 0,
            "remark"       => "交易订单退款",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderRefund["mchId"],
            "mchNo"             => $tradeOrderRefund["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_CASH_FROZEN,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_TRADE_ORDER_REFUND_CONFIRM_FROZEN_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "currency"          => $tradeOrderRefund['transSettleCurrency'],
            "orderId"           => $tradeOrderRefund['orderId'],
            "tradeNo"           => $tradeOrderRefund['tradeNo'],
            "refundId"          => $tradeOrderRefund['id'],
            "remark"            => "交易订单退款解冻冻结账户出账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
        return $mchAccountAccess['id'];
    }

    /**
     * @param $param
     * @param $tradeOrderRefund
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * @return string
     * 审核，退款金额，可提现出账，退款成功
     */
    private function handleConfirmCashOutTransAmount($param, $tradeOrderRefund, $mchAccount, $amount, $beforeAmount, $afterAmount) {
        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $tradeOrderRefund["mchId"],
            "mchNo"        => $tradeOrderRefund["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_TRADE_ORDER_REFUND,
            "accountType"  => ACCOUNT_TYPE_CASH,
            "orderId"      => $tradeOrderRefund['orderId'],
            "tradeNo"      => $tradeOrderRefund['tradeNo'],
            "refundId"     => $tradeOrderRefund['id'],
            "amount"       => -$amount,
            "currency"     => $tradeOrderRefund['transSettleCurrency'],
            "status"       => 1,
            "remark"       => "交易订单退款",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderRefund["mchId"],
            "mchNo"             => $tradeOrderRefund["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_TRADE_ORDER_REFUND_CONFIRM_CASH_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "currency"          => $tradeOrderRefund['transSettleCurrency'],
            "orderId"           => $tradeOrderRefund['orderId'],
            "tradeNo"           => $tradeOrderRefund['tradeNo'],
            "refundId"          => $tradeOrderRefund['id'],
            "remark"            => "交易订单退款",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
        return $mchAccountAccess['id'];
    }

    /**
     * @param $param
     * @param $tradeOrderRefund
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 退款手续费出账
     */
    private function handleConfirmRefundFee($param, $tradeOrderRefund, $mchAccount, $amount, $beforeAmount, $afterAmount) {

        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $tradeOrderRefund["mchId"],
            "mchNo"        => $tradeOrderRefund["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_TRADE_ORDER_REFUND,
            "accountType"  => ACCOUNT_TYPE_CASH,
            "orderId"      => $tradeOrderRefund['orderId'],
            "tradeNo"      => $tradeOrderRefund['tradeNo'],
            "refundId"     => $tradeOrderRefund['id'],
            "amount"       => -$amount,
            "currency"     => $tradeOrderRefund['transSettleCurrency'],
            "status"       => 1,
            "remark"       => "交易订单退款交易处理费出账",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderRefund["mchId"],
            "mchNo"             => $tradeOrderRefund["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_TRADE_ORDER_REFUND_CONFIRM_REFUND_FEE_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "orderId"           => $tradeOrderRefund['id'],
            "tradeNo"           => $tradeOrderRefund['tradeNo'],
            "refundId"          => $tradeOrderRefund['id'],
            "currency"          => $tradeOrderRefund['transSettleCurrency'],
            "remark"            => "交易订单退款交易处理费出账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }

}